import paho.mqtt.client as mqtt
import time
import paho.mqtt.publish as publish
from tables import Mqtt
from database import Session

HOST = "10.203.253.235"
PORT = 8080
client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))

def client_loop():
    print('connecting')
    client = mqtt.Client(client_id)
    client.username_pw_set("admin", "123456")
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(HOST, PORT, 60)
    client.loop_forever()

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("env")

def on_message(client, userdata, msg):
    text = msg.payload.decode("utf-8")
    text = text.replace('\n', '')
    text = text.replace('\r', '')

    print(text)
    items = text.split('!')[0]
    # print(items)
    items = items.split(',')
    # print(items)
    if len(items)>1:
        for item in items:
           name = item.split(':')[0]
           value = item.split(':')[1]
           # print("name: "+name)
           # print("value: "+value)
           session = Session()
           # 判断是否满了120条记录
           records = session.query(Mqtt).all()
           if len(records) == 1200:
               for i in range(1,4):
                   record = session.query(Mqtt).order_by(Mqtt.id).first()
                   session.delete(record)
                   session.commit()
           # 获取最大ID
           record = session.query(Mqtt).order_by(Mqtt.id.desc()).first()
           id = 1
           if record != None:
               id = record.id + 1
           data = Mqtt(id=id, name=name, value=value)
           session.add(data)
           session.commit()

def pub_message(topic, data):
    publish.single(topic, data, qos = 1,hostname=HOST,port=PORT, client_id=client_id)

if __name__ == '__main__':
    client_loop()
